import * as React from'react'
import { useEvent } from 'react-use'
import { MessageType } from '../../../src/utils/MessageHandler'
import { Task } from '../../../src/store/types'
import { vscode } from '../utils/vscode'
import styles from './HistoryPage.module.less'
import { useNavigate } from 'react-router'

export default React.memo(function() {
	const navigate = useNavigate()
	const [tasks, setTasks ] = React.useState<Task[]>([])

	function handleMessage(e: MessageEvent) {
		const message = e.data
		console.log('历史聊天页面收到消息', message)
		if(message.type === MessageType.getHistory) {
			message.data = message.data.sort((a: Task, b: Task) => {
				return b.firstMessage.createTime - a.firstMessage.createTime
			})
			setTasks([
				...message.data
			])	
		}
	}

	function handleClick(task: Task) {
		navigate('/chat/'+ task.taskId, {
			state: {
				taskId: task.taskId,
				message: [task.firstMessage]
			}
		})
	}

	useEvent('message', handleMessage)

	React.useEffect(() => {
		console.log('历史聊天页面')
		vscode.postMessage({
			type: MessageType.getHistory,
		})
		return () => {
			console.log('历史聊天页面卸载')
		}
	}, [])

	return (
		<>
			<div className={styles.history}>
				{tasks.map((task, index) => (
					<div key={index} className={styles['history-item']} onClick={() => handleClick(task)}>
						<div className={styles.icon}>
							<i className="codicon codicon-comment"></i>
						</div>
						<div className={styles.content}>
							<span>{task.firstMessage.message.content}</span>
						</div>
					</div>
				))}
			</div>
		</>
	)
})